package drds.server.sqlparser.visitor;

import java.util.List;

import drds.server.sqlparser.sqlobject.expression.Between;
import drds.server.sqlparser.sqlobject.expression.Expression;
import drds.server.sqlparser.sqlobject.expression.Variable;
import drds.server.sqlparser.sqlobject.expression.binary.BinaryExpression;
import drds.server.sqlparser.sqlobject.expression.data_type.DataType;
import drds.server.sqlparser.sqlobject.expression.data_type.Text;
import drds.server.sqlparser.sqlobject.expression.data_type.number.Numeric;

/**
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public class ExportParameterVisitorUtils {

	public static boolean exportParamterAndAccept(final List<Object> parameterList, List<Expression> expressionList) {
		for (int i = 0, size = expressionList.size(); i < size; ++i) {
			Expression expression = expressionList.get(i);

			Expression result = exportParameter(parameterList, expression);
			if (result != expression) {
				expressionList.set(i, result);
			}
		}

		return false;
	}

	public static Expression exportParameter(final List<Object> parameterList, final Expression expression) {
		if (expression instanceof Text) {
			Object value = ((Text) expression).getText();
			parameterList.add(value);
			return new Variable("?");
		}

		if (expression instanceof Numeric) {
			Object value = ((Numeric) expression).getNumber();
			parameterList.add(value);
			return new Variable("?");
		}

		return expression;
	}

	public static void exportParameter(final List<Object> parameterList, BinaryExpression x) {
		if (x.getLeft() instanceof DataType && x.getRight() instanceof DataType && x.getBinaryOperator().isRelational()) {
			return;
		}

		{
			Expression leftResult = ExportParameterVisitorUtils.exportParameter(parameterList, x.getLeft());
			if (leftResult != x.getLeft()) {
				x.setLeft(leftResult);
			}
		}

		{
			Expression rightResult = exportParameter(parameterList, x.getRight());
			if (rightResult != x.getRight()) {
				x.setRight(rightResult);
			}
		}
	}

	public static void exportParameter(final List<Object> parameterList, Between x) {
		{
			Expression result = exportParameter(parameterList, x.getBegin());
			if (result != x.getBegin()) {
				x.setBegin(result);
			}
		}

		{
			Expression result = exportParameter(parameterList, x.getEnd());
			if (result != x.getBegin()) {
				x.setEnd(result);
			}
		}

	}
}
